#include "lock.hpp"
#include "tools.hpp"

namespace thread
{
	Lock::Lock()
	{
		int ret = 0;
		if ((ret = ::pthread_mutex_init(&_mutex, 0)) != 0)
		{
			tools::LOG_ERR_MSG(ret, "Lock::lock pthread_mutex_init error");
		}
	}

	Lock::~Lock()
	{
		int ret = 0;
		if ((ret = ::pthread_mutex_destroy(&_mutex)) != 0)
		{
			tools::LOG_ERR_MSG(ret, "Lock::~Lock pthread_mutex_destroy error");
		}
	}

	void Lock::lock()
	{
		int ret = 0;
		if ((ret = ::pthread_mutex_lock(&_mutex)) != 0)
		{
			tools::LOG_ERR_MSG(ret, "Lock::lock pthread_mutex_lock error");	
		}
	}

	void Lock::unlock()
	{
		int ret = 0;
		if ((ret = ::pthread_mutex_unlock(&_mutex)) != 0)
		{
			tools::LOG_ERR_MSG(ret, "Lock::unlock pthread_mutex_unlock error");
		}
	}

	bool Lock::lock(long ms)
	{
		struct timespec ts;
		tools::get_abs_timespec(ms, ts);
		int ret = 0;
		ret = ::pthread_mutex_timedlock(&_mutex, &ts);
		if (ETIMEDOUT == ret)
		{
			return false;
		}

		if (0 != ret)
		{
			tools::LOG_ERR_MSG(ret, "Lock::lock pthread_mutex_timedlock error");
		}
		return (0 == ret);
	}

	bool Lock::try_lock()
	{
		return (::pthread_mutex_trylock(&_mutex) == 0);
	}
}


